<template>
  <div class="add-question">
    <h2>添加新题目</h2>
    <form @submit.prevent="handleSubmit">
      <div class="form-group">
        <label>题目内容：</label>
        <textarea 
          v-model="question.content" 
          rows="4" 
          required 
          placeholder="请输入题目内容"
        ></textarea>
      </div>

      <div class="form-group">
        <label>图片说明：</label>
        <input 
          type="text" 
          v-model="question.imageUrl" 
          placeholder="请输入图片URL（可选）"
        />
      </div>

      <div class="form-group">
        <label>提示信息：</label>
        <input 
          type="text" 
          v-model="question.hint" 
          placeholder="请输入提示信息（可选）"
        />
      </div>

      <div class="form-group">
        <label>答案：</label>
        <textarea 
          v-model="question.answer" 
          rows="4" 
          required 
          placeholder="请输入答案"
        ></textarea>
      </div>

      <div class="error-message" v-if="errorMsg">
        {{ errorMsg }}
      </div>

      <button type="submit" :disabled="isSubmitting">
        {{ isSubmitting ? '保存中...' : '保存题目' }}
      </button>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useQuestionStore } from '../stores/question'

const questionStore = useQuestionStore()
const isSubmitting = ref(false)
const errorMsg = ref('')
const question = ref({
  content: '',
  answer: '',
  imageUrl: '',
  hint: ''
})

async function handleSubmit() {
  if (isSubmitting.value) return
  
  errorMsg.value = ''
  isSubmitting.value = true
  
  try {
    console.log('提交的数据:', question.value)
    const result = await questionStore.addQuestion(question.value)
    console.log('服务器响应:', result)
    
    question.value = { content: '', answer: '', imageUrl: '', hint: '' }
    alert('题目添加成功！')
  } catch (error) {
    console.error('提交失败:', error)
    errorMsg.value = `添加失败：${error.message || '未知错误'}`
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.add-question {
  max-width: 600px;
  margin: 0 auto;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
}

textarea, input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

button {
  padding: 10px 20px;
  background: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background: #a8d5c2;
}

.error-message {
  color: red;
  margin: 10px 0;
  padding: 10px;
  background: #fff3f3;
  border-radius: 4px;
}
</style> 